<?php

include "common.php";


$realPath = 'server';
$sck = stream_socket_server("tcp://0.0.0.0:8989",$errno, $errstr);

    
while(true) {
	$conn = stream_socket_accept($sck);
	$buf = decode($conn);
	$classRet = preg_match('/Rpc-Class:\s(.*);/i', $buf, $class);
    $methodRet = preg_match('/Rpc-Method:\s(.*);/i', $buf, $method);
    $paramsRet = preg_match('/Rpc-Params:\s(.*);/i', $buf, $params);

     if($classRet && $methodRet) {
        $class = ucfirst($class[1]);
        $file = $realPath . '/' . $class . '.php';
        //判断文件是否存在，如果有，则引入文件
        if(file_exists($file)) {
            require_once $file;
            //实例化类，并调用客户端指定的方法
            $obj = new $class();
            //如果有参数，则传入指定参数
            if(!$paramsRet) {
                $data = $obj->$method[1]();
            } else {
                $data = $obj->$method[1](json_decode($params[1], true));
            }
            //把运行后的结果返回给客户端
            fwrite($conn, encode($data));
        } else {
            fwrite($conn, encode("class or method error"));
        }
	} else {
	    fwrite($conn, encode("class or method error"));
	}
	//关闭客户端
	fclose($conn);	
}
